package com.woniuxy.shiro.filter;
import com.woniuxy.shiro.JWTToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @ClassName JWTFilter
 * @Description JWT过滤器用于对JWT的验证
 * @Author 王维鑫
 * @Date 2021/5/13 0013 9:56
 * @Version 1.0
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {



    /**
     *@Author 王维鑫
     *@Description 判断请求是否有token的方法
     *@Param [request, response, mappedValue]
     *@return boolean
     **/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        //返回值true表示请求向下继续执行
        //判断请求头中是否包含token
        HttpServletRequest req= (HttpServletRequest) request;
        if(req.getHeader("token")!=null){
            //调用认证方法,认证结果就代表本次是否放行
            try {
                return executeLogin(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //返回值false shiro会抛出401异常
        return false;
    }


    /**
     *@Author 王维鑫
     *@Description 认证token
     *@Param [request, response]
     *@return boolean
     **/
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest req= (HttpServletRequest) request;
        //调用领域类中的方法执行认证
        Subject subject = SecurityUtils.getSubject();
        JWTToken jwtToken = new JWTToken(req.getHeader("token"));
        //让shiro通过领域类完成认证
        subject.login(jwtToken);//执行认证 不是登陆
        return true;
    }


    /**
     *@Author 王维鑫
     *@Description 跨域解决
     *@Param [request, response]
     *@return boolean
     **/
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        //处理跨域
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //如果请求方式是options，代表着是预检请求，因此，直接放行
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

}
